package com.alinesno.cloud.operation.cmdb.third.sms;
import java.io.StringWriter;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.alinesno.cloud.operation.cmdb.entity.SmsFailEntity;
import com.alinesno.cloud.operation.cmdb.entity.SmsSendEntity;
import com.alinesno.cloud.operation.cmdb.entity.SmsTemplateEntity;
import com.alinesno.cloud.operation.cmdb.repository.SmsFailRepository;
import com.alinesno.cloud.operation.cmdb.repository.SmsSendRepository;
import com.alinesno.cloud.operation.cmdb.repository.SmsTemplateRepository;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author WeiXiaoJin
 * @since 2018-01-23
 */
@Service
public class SmsSendService {

	//日志记录
	private static final Logger logger = LoggerFactory.getLogger(SmsSendService.class);

	/**
	 * 重置密码
	 */
	private String resetPassword = "SMS_126575232";

	/**
	 * 用户手机注册
	 */
	private String applyPhone  = "SMS_126630218";

	/**
	 * 用户身份验证
	 */
	private String userValidate = "SMS_126620228" ;

	/**
	 * 订单通知
	 */
	private String orderStatusNotice = "SMS_126580268" ;

	/**
	 * 签名
	 */
	private String signName = "云主机管理系统" ;

	@Autowired
	private SmsTemplateRepository smsTemplateRepository ; 
	
	@Autowired
	private SmsSendRepository smsSendRepository ; 
	
	@Autowired
	private SmsFailRepository smsFailRepository ; 

	/**
	 * 短信发送服务
	 */
	@Autowired
	private SmsApi trainingSmsApi ;

	private final static String OK = "OK" ;

	public SmsResponse sendValidateSms(String phone) {
		logger.debug("phone = {} , userValidate = {}" , phone , userValidate);
		SmsResponse smsResponse = createCode(phone , userValidate ) ;
		return smsResponse ;
	}

	public SmsResponse sendResetPasswordSms(String phone ) {
		logger.debug("phone = {} , resetPassword = {}" , phone , resetPassword);

		SmsResponse smsResponse = createCode(phone , resetPassword ) ;
		return smsResponse ;
	}

	public SmsResponse sendApplyPhoneSms(String phone) {
		logger.debug("phone = {} , applyPhone = {}" , phone , applyPhone);
		SmsResponse smsResponse = createCode(phone , applyPhone) ;
		return smsResponse ;
	}

	/**
	 * 请求代码
	 * @param phone
	 * @param userValidate2
	 * @return
	 */
	private SmsResponse createCode(String phone, String template) {

		String validateCode =  SmsUtils.generateVerificationCode(4) ;

		JSONObject json = new JSONObject();
		json.put(AliyunSmsEunms.CODE.value(),validateCode) ;

		SmsResponse response = sendSms(json , phone , template) ;

		Map<String , Object> params = new HashMap<String , Object>() ;
		params.put(AliyunSmsEunms.CODE.value(),validateCode) ;
		response.setParams(params);

		return response ;
	}

	/**
	 * 发送通知通知
	 * @return
	 */
	private SmsResponse sendSms(JSONObject json , String phone , String template) {

		String validateCode = json.getString(AliyunSmsEunms.CODE.value())==null?"-1":json.getString(AliyunSmsEunms.CODE.value()) ;
		SmsRequest smsRequest = new SmsRequest() ;
		smsRequest.setSignName(signName);
		smsRequest.setTemplate(json.toJSONString());
		smsRequest.setPhone(phone);
		smsRequest.setTemplateCode(template);

		SmsResponse r = trainingSmsApi.sendSms(smsRequest) ;
		r.setBizId(System.currentTimeMillis()+"");

		SmsSendEntity e = new SmsSendEntity() ;
		e.setAddTime(new Timestamp(System.currentTimeMillis())) ;

		e.setPhone(phone);
		e.setSignName(signName);
		e.setTemplateCode(template);
		e.setBizId(r.getBizId());
		e.setValidateCode(validateCode);

		SmsTemplateEntity templateEntity = smsTemplateRepository.findAllByTemplate(template) ;
		if(templateEntity != null) {
			e.setTemplate(templateEntity.getTemplateContent());
			VelocityContext context = new VelocityContext();

			Set<String> keys = json.keySet() ;
			for(String k : keys) {
				String v = json.getString(k) ;
				context.put(k, v) ;
			}

			e.setContent(templateToContent(context , templateEntity.getTemplateContent()));

			if(OK.equals(r.getCode())) {
				smsSendRepository.save(e) ; 
			}else {
				SmsFailEntity ef = new SmsFailEntity() ;
				BeanUtils.copyProperties(e, ef);
				smsFailRepository.save(ef) ; 
			}
		}

		return r ;
	}

	/**
	 * 使用同一个签名，对同一个手机号码发送短信验证码，1条/分钟，5条/小时，10条/天
	 * @param phone
	 * @return
	 */
	@SuppressWarnings("unused")
	private boolean validateSendTime(String phone) {

		return false ;
	}

	public String templateToContent(VelocityContext context , String template) {
		Velocity.init();
        StringWriter stringWriter = new StringWriter();
        Velocity.evaluate(context, stringWriter, "mystring", template);

        return stringWriter.toString() ;
	}

	public SmsResponse sendOrderStatusSms(String phone, String status, String remark) {
		JSONObject json = new JSONObject();
		json.put(AliyunSmsEunms.STATUS.value(),status) ;

		if(StringUtils.isNoneBlank(remark) && remark.length() > 20) {
			remark = remark.substring(0, 19) ;
		}

		json.put(AliyunSmsEunms.REMARK.value(),remark) ;
		return sendSms(json , phone , orderStatusNotice) ;
	}

}






























